package com.jrx.anytxn.transaction.job.coupon.config;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.transaction.config.AnytxnBatchProperties;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.job.coupon.dto.CustomerRightsDTO;
import com.jrx.anytxn.transaction.job.coupon.step.CouponMonthlyProcessor;
import com.jrx.anytxn.transaction.job.coupon.step.CouponMonthlyWriter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName CouponMonthlyConfiguration
 *
 * @author lujianyou
 * @version 1.0
 * @description 每月 1~24 号 统计消费额，发放对应的权益
 * @date 2021/11/9 10:45
 **/
@Configuration
@EnableConfigurationProperties(AnytxnBatchProperties.class)
@EnableBatchProcessing
public class CouponMonthlyConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(CouponMonthlyConfiguration.class);

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private CouponMonthlyProcessor couponMonthlyProcessor;
    @Autowired
    private CouponMonthlyWriter couponMonthlyWriter;

    @Bean
    public Job couponMonthlyJob(){
        return jobBuilderFactory.get("couponMonthlyJob")
                .incrementer(new RunIdIncrementer())
                .start(couponMonthlyStep())
                .build();
    }

    /**
     *  每月1-24号统计消费额赠送相应权益
     * @return
     */
    @Bean
    public Step couponMonthlyStep(){
        return stepBuilderFactory.get("couponMonthlyStep")
                .<AmLoanMainInfo, CustomerRightsDTO>chunk(anytxnBatchProperties.getCouponMonthlyConfig().getChunkLimit())
                //表示一批处理100条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(couponMonthlyReader())
                .processor(couponMonthlyProcessor)
                .writer(couponMonthlyWriter)
                .transactionManager(platformTransactionManager)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                //多线程
                .throttleLimit(anytxnBatchProperties.getCouponMonthlyConfig().getThrottleLimit())
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<AmLoanMainInfo> couponMonthlyReader() {
        MyBatisCursorItemReader<AmLoanMainInfo> itemStreamReader = new MyBatisCursorItemReader<>();
        itemStreamReader.setSaveState(false);
        itemStreamReader.setSqlSessionFactory(sqlSessionFactory);
        //查询方法
        itemStreamReader.setQueryId("com.jrx.anytxn.transaction.mapper.ext.ExtAmLoanMainInfoMapper." +
                "sumByCustomerIdAndDateRangeAndLoanTypeForBatch");
        Map<String,Object> map = new HashMap<>(8);

        //查询参数设置
        map.put("tenantId","101");
        map.put("loanType","4");
        map.put("productId", Constants.DEFAULT_PRODTCT_CODE);
        map.put("startTime", DateUtils.getDayOfCurrentMonthDay(1) + " 00:00:00");
        map.put("endTime",DateUtils.getDayOfCurrentMonthDay(24) + " 23:59:59");
        itemStreamReader.setParameterValues(map);

        SynchronizedItemStreamReader<AmLoanMainInfo> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(itemStreamReader);
        return synchronizedItemStreamReader;

    }


}
